<?php
class LoginApp extends CommonApp {

    //男-0，女-1，老师1，学生2，院系管理员0，cxcyxy管理员3
    private  $type = array('0','1','3');//院系，老师，cxcyxy

    //登录界面
    public function indexAct(){
        //用户已登陆直接跳转到通知页面
        $this->redirect2();
        $this->display();
    }

    //注册界面
    public function registerAct(){
        //用户已登陆直接跳转到通知页面
        $this->redirect2();
        //college
        $result = M('admin.category')->item2submenu('college',array('level'=>'1'));//学院
        $this->assign('result',$result);
        $this->display();
    }

    //重置密码
    public  function getpasswordAct(){
        $this->redirect2();
        $this->display();
    }

   	//登录界面验证
    public function loginAct(){
    	if($_POST){
    		//用户名判断
    		if(empty($_POST['username']))
    			$this->ajaxReturn(300,'用户名不能为空！');
    		//密码判断
    		if(!My::is_string($_POST['password']))
    			$this->ajaxReturn(300,'密码不能为空！');
    		//判断验证码
    		$verify = new Verify();
            if(!$verify->check(My::arr2var($_POST,'verify')))
              $this->ajaxReturn(300,'验证码错误!');
            if($_POST['grade'] == '1')//普通用户登陆
                $result = DB('homeuser')->where("username='{$_POST['username']}' AND password='".md5(md5($_POST['password']))."'")->cache()->find();
            else if($_POST['grade'] == '0'){
                if($_POST['username']=='admin')
                    $this->ajaxReturn(300,'沒有该管理员账户！');
                $result = DB('user')->where("username='{$_POST['username']}' AND password='".md5(md5($_POST['password']))."'")->field('id,username,email,image,role_id')->cache()->find();
                if(!is_array($result))
                    $this->ajaxReturn(300,'用户名或密码错误!');
                if($result['role_id'] == '9')
                    $result['type'] = '0';//院系身份
                else if($result['role_id'] == '8')
                    $result['type'] = '3';//cxcyxy身份
                if(empty($result['image']))
                    $result['image'] = 'share/images/admin.jpg';
                $result['college'] = $this->college($result['id']);
            }
            if(is_array($result)){
                self::doLogin($result['id'],'homeuser',$result);
                if($result)
                    $this->ajaxReturn(200,array('message'=>'登陆成功！','type'=>$result['type']));
                else
                    $this->ajaxReturn(300,'登陆失败（设置登录状态时异常）');
            }else
                $this->ajaxReturn(300,'用户名或密码错误!');
    	}
    }

    //注册页面
    public function register_codeAct(){
    	if($_POST){
    		//用户名
    		if(!My::is_string($_POST['username'],array('c')))
    			$this->ajaxReturn(300,array('message'=>'真实姓名填写有误！','name'=>'username'));
            //学号
            if($_POST['type'] == '2')
                if(empty($_POST['params']['student_id']))
                    $this->ajaxReturn(300,array('message'=>'请填写学号！','name'=>'student_id'));
    		//院系
            if(empty($_POST['college']))
                $this->ajaxReturn(300,array('message'=>'请选择院系！','name'=>'college'));
            //专业
            if($_POST['type'] == '2')
                if(empty($_POST['class']))
                    $this->ajaxReturn(300,array('message'=>'请选择专业！','name'=>'class'));
            //邮箱
            if(!My::is_email($_POST['email']))
              $this->ajaxReturn(300,array('message'=>'邮箱填写有误！','name'=>'email'));
            //密码判断
            if(!My::is_string($_POST['password']) || strlen($_POST['password']) < '6' || strlen($_POST['password']) > '20')
                $this->ajaxReturn(300,array('message'=>'密码由6-20位的英文字母、数字和特殊符号组成','name'=>'password'));
            //确认密码判断
            if(!My::is_string($_POST['password2']))
                $this->ajaxReturn(300,array('message'=>'确认密码填写有误！','name'=>'password2'));
            if($_POST['password2'] !== $_POST['password'])
                $this->ajaxReturn(300,array('message'=>'两次密码输入不一致！','name'=>'password2'));
            //手机号
            if(!My::is_tel($_POST['number']))
                $this->ajaxReturn(300,array('message'=>'手机号格式错误！','name'=>'number'));
//            //判断验证码
//            $verify = new Verify();
//            if(!$verify->check(My::arr2var($_POST,'verify')))
//                $this->ajaxReturn(300,array('message'=>'验证码错误！','name'=>'verify'));
            $result = DB('homeuser')->where("number='{$_POST['number']}'")->find();
            if($result)
              $this->ajaxReturn(300,array('message'=>'该手机号已注册，请重新填写！','name'=>'number'));
            $_POST['complete'] = '1';//信息完整度
            $_POST['password'] = md5(md5($_POST['password']));
            $_POST['adddate'] = date("Y-m-d H:i:s");
            if($_POST['sex'] == '0' && $_POST['type'] == '1')//男老师
                $_POST['image'] = 'share/images/teacher_0.jpg';
            else if($_POST['sex'] == '1' && $_POST['type'] == '1')//女老师
                $_POST['image'] = 'share/images/teacher_1.jpg';
            else if($_POST['sex'] == '1' && $_POST['type'] == '2')//女学生
                $_POST['image'] = 'share/images/student_1.jpg';
            else if($_POST['sex'] == '0' && $_POST['type'] == '2')//男学生
                $_POST['image'] = 'share/images/student_0.jpg';
            if($_POST['type'] == '1'){
                unset($_POST['params']);
                unset($_POST['class']);
            }
            $ok = DB('homeuser')->clear()->add($_POST);
            if($ok>=0)	$this->ajaxReturn(200,"注册成功，请前往登陆");
            else		$this->ajaxReturn(300,"注册失败");
    	}
    }

    //重置密码
    public function passwordAct(){
        if($_POST){
            //密码判断
            if(!My::is_string($_POST['password']))
                $this->ajaxReturn(300,array('message'=>'密码填写有误！','name'=>'password'));
            //确认密码判断
            if(!My::is_string($_POST['password2']))
                $this->ajaxReturn(300,array('message'=>'确认密码填写有误！','name'=>'password2'));
            if($_POST['password2'] !== $_POST['password'])
                $this->ajaxReturn(300,array('message'=>'两次密码输入不一致！','name'=>'password2'));
            //手机号
            if(!My::is_tel($_POST['number']))
                $this->ajaxReturn(300,array('message'=>'手机号格式错误！','name'=>'number'));
            $result = DB('homeuser')->where("number='{$_POST['number']}'")->find();
            if(!$result)
                $this->ajaxReturn(300,array('message'=>'该手机号还未注册！','name'=>'number'));
            $_POST['password'] = md5(md5($_POST['password']));
            $result = DB('homeuser')->where("number='{$_POST['number']}'")->save($_POST);
            if($result)
                $this->ajaxReturn(200,'密码重置成功，请重新登陆！');
        }
    }

    //注册页面及短信服务
    public function smsAct(){
        if($_POST){
            if(!My::is_tel($_POST['number']))
                $this->ajaxReturn(300,array('messaga'=>'手机号格式错误!','name'=>'number'));
            $result = DB('homeuser')->where("number='{$_POST['number']}'")->find();
            if(!$result && $_POST['tab'] == 'getpassword')
                $this->ajaxReturn(300,array('message'=>'该手机号还未注册！','name'=>'number'));
            else if($result && $_POST['tab'] == 'register')
                $this->ajaxReturn(300,array('message'=>'该手机号已被注册！','name'=>'number'));
            $Sendsms = new Sendsms();
            $result = $Sendsms->sms($_POST['number']);
//                         $result['result'] = 'OK';
//                         $result['code'] = '123';
            if($result['result'] == 'OK') $this->ajaxReturn(200,$result['code']);
        }else $this->display();
    }

    //微信验证登陆
    public function oauth_loginAct(){
        if(My::is_id(My::arr2var($_GET,'id'))){
            $_SESSION['memberid'] = $_GET['id'];
            $_SESSION['grade'] = $_GET['grade'];
            Oauth2::getInstance()->weixinLogin();
        }
        $this->display();
    }

    //微信验证登陆
    public function oauthAct(){
        if(!My::is_weixin())
            $this->ajaxReturn(300,'请在微信端进行授权！');
        if($_POST){
            //用户名判断
            if(empty($_POST['username']))
                $this->ajaxReturn(300,'用户名不能为空！');
            //密码判断
            if(!My::is_string($_POST['password']))
                $this->ajaxReturn(300,'密码不能为空！');
            //判断验证码
            $verify = new Verify();
            if(!$verify->check(My::arr2var($_POST,'verify')))
                $this->ajaxReturn(300,'验证码错误!');
            if($_POST['grade'] == '1')//普通用户登陆
                $result = DB('homeuser')->where("username='{$_POST['username']}' AND password='".md5(md5($_POST['password']))."'")->field('id')->cache()->find();
            else if($_POST['grade'] == '0'){
                $result = DB('user')->where("username='{$_POST['username']}' AND password='".md5(md5($_POST['password']))."'")->field('id')->cache()->find();
            }
            if(is_array($result)){
                $result['grade'] = $_POST['grade'];
                $this->ajaxReturn(200,'验证成功，正在授权，请稍等...!','','',$result);
            }else
                $this->ajaxReturn(300,'用户名或密码错误!');
        }
    }

    //oauth回调
    public function callbackAct(){
        $host = My::arr2var($_GET,'host',$_SERVER['HTTP_HOST']);
        $is_https =  My::arr2var($_GET,'https');
        if($host!=$_SERVER['HTTP_HOST'] or $is_https!=My::is_https())
            redirect(($is_https ? 'https' : 'http')."://".$host.$_SERVER["REQUEST_URI"]);
        $type = My::arr2var($_GET,'type');
        if(!in_array(strtoupper($type), Oauth2::getInstance()->getOauthType()))
            $this->ajaxReturn(404,'未知的第三方登录类型！');
        $result = Oauth2::getInstance()->handleCallback(My::arr2var($_GET,'type'),My::arr2var($_GET,'code'));
        $oauth_type=C('oauth_type');
        if(!My::arr2var($result,'openid'))
            $this->ajaxReturn(404,'获取'.$oauth_type[$type].'用户信息失败！');
        $data['id'] = My::arr2var($_SESSION,'memberid');
        $data['openid'] = My::arr2var($result,'openid');
        if(My::arr2var($_SESSION,'grade') == '1'){
            $ok = DB('homeuser')->clear()->save($data);
        }else if($_SESSION['grade'] == '0')
            $ok = DB('user')->clear()->save($data);
        if($ok>0)
            redirect(Router::encodeUrl("index.php?app=Login&act=oauth_success"));
    }

    public function oauth_successAct(){
        $this->display();
    }

  	/**
     * 设置登录状态数据操作
     * @param int $memberid 用户id
     * @param string $login_type 问卷类型
     */
    private function doLogin($memberid, $login_type,$result){
        if(!My::is_id($memberid)) return false;
        //当前登录用户的信息
        //$result = DB($login_type)->field('password',true)->where('id='.$memberid)->find();
        //if(!is_array($result)) return false;
        //更新当前登录IP/登录时间/登出时间
        DB($login_type)->field('login_ip')->where("id={$memberid}")->save(array('login_ip'=>get_client_ip()));
        //登录次数++
        //DB($login_type)->where('id='.$memberid)->setInc('hit');
        // $result['params'] = My::decodeJson($result['params']);
        $result['memberid'] = $memberid;
        //已有memberid，此处去除id
        unset($result['id']);
        unset($result['password']);
        //设置前台用户登录session数据
        $_SESSION['member'] = $result;
        return true;
    }

    //联动
    public function getclassAct(){
        $option = "<option value='' selecct='selected'>请选择专业...</option>";
        if(!empty($_GET['id'])){
            $result = M('admin.category')->id2submenu($_GET['id']);//专业
            foreach($result as &$value)
                $option .= "<option value=".$value['id'].">".$value['title']."</option>";
            $this->ajaxReturn(200,$option);
        }else $this->ajaxReturn(200,$option);
    }

    /**
     * 用户退出
     */
    public function logoutAct(){
        $this->checkLogin();
        $memberid = My::arr2var($_SESSION,'member.memberid');
        DB('homeuser')->field('loginout_time')->where("id={$memberid}")->save(array('loginout_time'=>date('Y-m-d H:i:s')));
        //删除本系统的session
        $_SESSION['member'] = '';
        rm_dir(DATA_DIR.'Cache');//cache缓存
        redirect(Router::encodeUrl('index.php?app=Login&act=index'));
    }

    //重定向
    public function redirect2(){
        //用户已登陆直接跳转到通知页面
        if(isset($_SESSION['member'])){
            if(My::user('member.type') == '2')
                redirect(Router::encodeUrl('index.php?app=Myproject&act=student'));
            else if(in_array(My::user('member.type'),$this->type))
                redirect(Router::encodeUrl('index.php?app=Myproject&act=teacher'));
        }
    }

    //清除缓存
    function clear(){
        rm_dir(DATA_DIR.'Cache');//cache缓存
        rm_dir(DATA_DIR.'Field');//数据库模型缓存
        //rm_dir(DATA_DIR.'Log');//日志缓存
        //rm_dir(DATA_DIR.'Session');//Session文件
        $this->ajaxReturn(200, '已清空所有缓存文件！');
    }

    //院系id
    function college($id){
        switch ($id) {
            case '4':
                $college = '360';
                break;
            case '5':
                $college = '344';
                break;
            case '6':
                $college = '345';
                break;
            case '7':
                $college = '346';
                break;
            case '8':
                $college = '347';
                break;
            case '9':
                $college = '348';
                break;
            case '10':
                $college = '349';
                break;
            case '11':
                $college = '350';
                break;
            case '12':
                $college = '351';
                break;
            case '13':
                $college = '352';
                break;
            case '14':
                $college = '354';
                break;
            case '15':
                $college = '355';
                break;
            case '16':
                $college = '357';
                break;
            case '17':
                $college = '353';
                break;
            case '18':
                $college = '379';
                break;
            case '19':
                $college = '387';
                break;
            case '20':
                $college = '392';
                break;
            default:
                # code...
                break;
        }
        return $college;
    }
}